/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.web30.semantic.core.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.web30.semantic.core.model.MetaRepository;
import org.web30.semantic.core.model.ResourceRepository;
import org.web30.semantic.core.model.Web30Exception;

/**
 *
 * @author xiazy
 */
public class CrawlerTask implements Runnable {

    private ResourceRepository resource = null;
    
    private Map metaContainers = null;

    private boolean stop = false;

    private int interval = 1; // 1 sec

    public synchronized void setStop(boolean flag){
        this.stop = flag;
    }

    public synchronized boolean isStop(){
        return this.stop ;
    }
    public CrawlerTask(ResourceRepository resource, Map metaContainers) {
        this.resource = resource;
        this.metaContainers = metaContainers;
    }

    public void run() {
        try{
            while(!this.isStop()){
                try {
                    this.resource.initRepository();
                    while (this.resource.hasResource()) {
                        Iterator metaIt = this.metaContainers.keySet().iterator();
                        while (metaIt.hasNext()) {
                            MetaRepository metaRep = (MetaRepository) this.metaContainers.get(metaIt.next());
                            metaRep.initRepository();
                            metaRep.addMetaData(this.resource.getNextResource());
                            metaRep.closeRepository();
                        }
                    }
                    this.resource.closeRepository();
                } catch (Web30Exception ex) {
                    Thread.sleep(interval * 1000);
                    continue;
                }
                Thread.sleep(interval * 1000);
            }
        }catch (InterruptedException e) {
            return;
        }
    }
}
